package org.com.system.util.model;

import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.struts2.ServletActionContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class Action<E> extends ActionSupport{

	private static final long serialVersionUID = 1L;
	
	private ActionValues<String,Object> values=null;
	private static ActionContext context = ActionContext.getContext();
	private static Map<String,Object> session=ActionContext.getContext().getSession();
	private static ServletContext servletContext=ServletActionContext.getServletContext();

	public ActionValues<String,Object> getValues() {
		return values;
	}

	public void setValues(ActionValues<String,Object> values) {
		this.values = values;
	}
	
	/**
	 * 得到Spring容器里的Bean
	 * @param beanName
	 * @return
	 */
	public Dao<?> getDao(String beanName){
		WebApplicationContext applicationContext  = WebApplicationContextUtils.getWebApplicationContext(servletContext);
		return (Dao<?>)applicationContext.getBean(beanName);
	}
	
	/**
	 * 得到请求Session
	 * @return
	 */
	public Map<String,Object> getSession(){
		if(null==session){
			session=ActionContext.getContext().getSession();
		}
		return session;
	}
	
	public void write(String data){
		HttpServletResponse response =(HttpServletResponse) context.get(ServletActionContext.HTTP_RESPONSE);
		ServletActionContext.getRequest();
		PrintWriter out=null;
		try{
            out=response.getWriter();
            out.println(data);
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	public void write(Object obj){
		write(JSONObject.fromObject(obj).toString());
	}
	
	public void write(List<?> data){
		write(JSONArray.fromObject(data).toString());
	}
	
}
